package safeCommitter.core.launcher;

import java.io.IOException;
import java.net.URL;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.launching.JavaRuntime;

import safeCommitter.core.template.Activator;

/**
 * Responsible for computing the classPath of the project.
 * 
 */
public class SCClasspathComputer {

	/**
	 * Retrieves all the classPath entries from a given project in the
	 * host-Eclipse.
	 * 
	 * @param project
	 * @return
	 * @throws CoreException
	 */
	@SuppressWarnings("deprecation")
	public static String[] computeClasspath(final IJavaProject project)
			throws CoreException {
		String[] projectPath = JavaRuntime
				.computeDefaultRuntimeClassPath(project);
		Boolean containsTestNG = false;
		Boolean containsJunit = false;

		for (String path : projectPath) {
			if (path.contains("testng-jdk15.jar")) {
				containsTestNG = Boolean.TRUE;
			}
			if (path.contains("junit.jar")) {
				containsJunit = true;
			}

		}
		Integer additionalPaths = containsTestNG ? 1 : 2;
		if (!containsJunit) {
			additionalPaths++;
		}

		String[] classPath = new String[projectPath.length + additionalPaths];
		System.arraycopy(projectPath, 0, classPath, additionalPaths,
				projectPath.length);
		Activator plugin = Activator.getDefault();
		URL url = plugin.getBundle().getEntry("/");
		try {
			classPath[0] = Platform.asLocalURL(new URL(url, "bin")).getFile();
			if (!containsTestNG) {
				classPath[1] = Platform.asLocalURL(
						new URL(url, "testng-jdk15.jar")).getFile();
			}
			if (!containsJunit) {
				classPath[1] = Platform.asLocalURL(new URL(url, "junit.jar"))
						.getFile();
			}

		} catch (IOException e) {
			IStatus status = new Status(IStatus.ERROR, plugin.getDescriptor()
					.getUniqueIdentifier(), IStatus.OK,
					"Could not determine path", e);
			throw new CoreException(status);
		}
		return classPath;
	}

}
